package gw.com.android.ui.home;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import www.com.library.view.XRecyclerView;

/**
 * @author jett
 * @since 2018-11-12.
 */
public class HomeRecyclerView extends XRecyclerView {

    private int mY;

    public HomeRecyclerView(Context context) {
        super(context);
    }

    public HomeRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HomeRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        if (mScrollFrozen) {
            return false;
        }
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mY = (int) e.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int currY = (int) e.getY();
                if (currY - mY > 0 && isTop()) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                mY = currY;
                break;
            case MotionEvent.ACTION_UP:
                mY = 0;
                break;
        }
        return super.onInterceptTouchEvent(e);
    }

    private boolean isTop() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
        if (layoutManager != null) {
            int firstPosition = layoutManager.findFirstVisibleItemPosition();
            return firstPosition <= 1;
        }
        return false;
    }

}
